import request from 'request';
import {FormOptions, Options} from "./bark.dto";

const defaults = {
  key: process?.env?.BARK_KEY,
  baseUrl: 'https://api.day.app'
};
export class Bark {
  opts: Options;
  constructor(opts: Options) {
    this.opts = Object.assign({}, defaults, opts);
    if (!this.validate()) return;
  }

  push (data: FormOptions) {
    return new Promise((resolve, reject) => {
      request({
        url: this.opts.baseUrl + '/' + this.opts.key,
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        form: data
      }, (err: Error, res, body) => {
        if (err) return reject(err)
        if (res && res.statusCode === 200) {
          return resolve(body)
        }
        return new Error(body.message)
      })
    })
  }

  validate(): boolean {
    if (!this.opts.key) {
      throw new Error('Bark key cannot be undefined.');
    }
    return true;
  }
}
